package com.distribute.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.distribute.common.Constant;
import com.distribute.dao.TSysAclMapper;
import com.distribute.dao.TSysRoleAclMapper;
import com.distribute.dao.TSysRoleUserMapper;
import com.distribute.entity.TSysAcl;
import com.distribute.entity.TSysAclExample;
import com.distribute.entity.TSysRoleAcl;
import com.distribute.entity.TSysRoleAclExample;
import com.distribute.entity.TSysRoleUser;
import com.distribute.entity.TSysRoleUserExample;
import com.distribute.service.SysAclService;
import com.google.common.collect.Multimap;

@Service
public class SysAclServiceImpl implements SysAclService{
	
	@Autowired
	private TSysAclMapper sysAclDao;
	@Autowired
	private TSysRoleUserMapper sysRoleUserDao;
	@Autowired
	private TSysRoleAclMapper sysRoleAclDao;

	@Override
	public List<TSysAcl> listByUserId(long userId) {
		if(userId == Constant.ADMIN_USER) {
			return listAll();
		} else {
			TSysRoleUserExample roleUserExample = new TSysRoleUserExample();
			roleUserExample.createCriteria()
				.andUserIdEqualTo(userId)
				.andStatusEqualTo(true);
			List<TSysRoleUser> roleUserList = sysRoleUserDao.selectByExample(roleUserExample);
			if(CollectionUtils.isNotEmpty(roleUserList)) {
				List<Long> roleIds = roleUserList.stream()
						.map(p -> p.getRoleId()).collect(Collectors.toList());
				
				TSysRoleAclExample roleAclExample = new TSysRoleAclExample();
				roleAclExample.createCriteria().andStatusEqualTo(true).andRoleIdIn(roleIds);
				List<TSysRoleAcl> roleAcls = sysRoleAclDao.selectByExample(roleAclExample);
				if(CollectionUtils.isNotEmpty(roleAcls)) {
					Set<Long> aclIdSet = roleAcls.stream()
							.map(p -> p.getAclId()).collect(Collectors.toSet());
					List<Long> aclIdList = aclIdSet.stream()
							.map(p -> p).collect(Collectors.toList());
					TSysAclExample aclExample = new TSysAclExample();
					aclExample.createCriteria().andStatusEqualTo(true)
						.andIdIn(aclIdList);
					aclExample.setOrderByClause(" parent_id asc, seq asc ");
					return sysAclDao.selectByExample(aclExample);
				}
			}
		}
		return null;
	}

	private List<TSysAcl> listAll() {
		TSysAclExample aclExample = new TSysAclExample();
		aclExample.setOrderByClause(" parent_id asc, seq asc ");
		aclExample.createCriteria().andStatusEqualTo(true);
		return sysAclDao.selectByExample(aclExample);
	}

	public void  setTreeAcl(Collection<TSysAcl> parentAclList, Multimap<Long, TSysAcl> aclMap, List<TSysAcl> sysAclTree) {
		if(CollectionUtils.isNotEmpty(parentAclList)) {
			for (TSysAcl sysAcl : parentAclList) {
				sysAclTree.add(sysAcl);
				setTreeAcl(aclMap.get(sysAcl.getId()), aclMap, sysAclTree);
			}
		}
	}

}